import PlayerCtrl from "../player/PlayerCtrl";
import PlayerData from "../player/PlayerData";
import { NetDefine } from "../../gamenet/protobufs/NetDefine";
const websocket = require("websocket");
const auth = require("auth");
const { ccclass, property } = cc._decorator;

@ccclass
export default class Login extends cc.Component {
    playerData: PlayerData = null;
    onLoad() {
        let service_handles = {};
        service_handles[NetDefine.ProtocolDefine.Auth] = this.onAuthRecv.bind(this);
        websocket.register_services_handler(service_handles);
        new PlayerCtrl();
        this.playerData = PlayerCtrl.data;
    }

    start() {
        this.playerData.vo.guestKey = cc.sys.localStorage.getItem("guest_key");
    }

    onBtnGuest() {
        auth.guest_login(this.playerData.vo.guestKey);
    }

    onBtnWechat() {

    }

    onAuthRecv(stype, ctype, body) {
        cc.log(body, ctype);
        switch (ctype) {
            case NetDefine.CmdDefine.Auth.GUEST_LOGIN: {
                if (body.status != NetDefine.Response.OK) {
                    return;
                }
                this.onGuestLoginSuc(body.nick, body.usex, body.uface, body.uvip, body.ukey);
                cc.director.loadScene(`ServerFuncHome`);
                break;
            }
            case NetDefine.CmdDefine.Auth.RELOGIN: {
                cc.log(`账号在其他地方登录`);
                break;
            }
        }
    }

    onGuestLoginSuc(nick, sex, face, vip, guestKey) {
        let playerVO = this.playerData.vo;
        playerVO.nickName = nick;
        playerVO.sex = sex;
        playerVO.icon = face;
        playerVO.vip = vip;

        if (!playerVO.guestKey != guestKey) {
            playerVO.guestKey = guestKey;
            cc.sys.localStorage.setItem("guest_key", guestKey);
        }
    }
}
